"""法律思维训练路由"""
from fastapi import APIRouter, HTTPException, Body
from typing import Dict, Any, Optional, List
from app.services.legal_thinking_service import legal_thinking_service
from app.services.question_technique_service import question_technique_service

router = APIRouter()


@router.post("/legal-thinking/analyze")
async def analyze_thinking_process(
    user_id: str = Body(...),
    question_id: str = Body(...),
    user_answer: str = Body(...),
    user_notes: str = Body(...),
    correct_answer: str = Body(...),
    question_content: str = Body(...),
    question_explanation: str = Body("")
):
    """分析用户的法律思维过程"""
    try:
        result = await legal_thinking_service.analyze_thinking_process(
            user_id,
            question_id,
            user_answer,
            user_notes,
            correct_answer,
            question_content,
            question_explanation
        )
        return result
    except Exception as e:
        import traceback
        print(f"分析思维过程错误: {e}")
        print(traceback.format_exc())
        # 返回默认结果，避免前端报错
        from datetime import datetime
        return {
            "thinking_quality_score": 70,
            "strengths": ["能够尝试分析问题"],
            "weaknesses": ["需要加强法律条文理解"],
            "thinking_pattern": "基础思维模式",
            "reasoning_chain": {},
            "improvement_suggestions": [
                "加强法律条文的学习和理解",
                "提高逻辑推理能力",
                "多进行案例分析训练"
            ],
            "legal_knowledge_gaps": [],
            "analysis_timestamp": datetime.now().isoformat(),
            "error": str(e)
        }


@router.get("/legal-thinking/training-plan/{user_id}")
async def get_thinking_training_plan(
    user_id: str,
    period_days: int = 30
):
    """获取法律思维训练计划"""
    plan = await legal_thinking_service.generate_thinking_training_plan(
        user_id,
        period_days
    )
    return plan


@router.post("/legal-thinking/feedback")
async def provide_thinking_feedback(
    user_id: str = Body(...),
    question_id: str = Body(...),
    user_thinking: str = Body(...),
    question_content: Optional[str] = Body(None)
):
    """提供实时思维反馈"""
    feedback = await legal_thinking_service.provide_thinking_feedback(
        user_id,
        question_id,
        user_thinking,
        question_content
    )
    return feedback


@router.post("/legal-thinking/analyze-question")
async def analyze_question(
    question_content: str = Body(...),
    options: Optional[List[str]] = Body(None)
):
    """分析题目结构"""
    result = await question_technique_service.analyze_question_structure(
        question_content,
        options
    )
    return result


@router.post("/legal-thinking/guide-reasoning")
async def guide_reasoning(
    question_content: str = Body(...),
    user_notes: Optional[str] = Body(None)
):
    """引导推理过程"""
    from app.ai.legalbert_service import get_legalbert_service
    legalbert = get_legalbert_service()
    
    # 提取推理链条
    reasoning_chain = await legalbert.extract_legal_reasoning_chain(
        question_content,
        user_notes
    )
    
    # 提取关键事实
    key_facts = await legalbert.extract_key_facts(question_content)
    
    # 检测陷阱
    traps = await legalbert.detect_question_traps(question_content)
    
    return {
        "reasoning_chain": reasoning_chain,
        "key_facts": key_facts,
        "traps": traps,
        "guidance": {
            "next_steps": _generate_reasoning_guidance(reasoning_chain, key_facts),
            "warnings": _generate_trap_warnings(traps)
        }
    }


@router.post("/legal-thinking/technique-analysis")
async def technique_analysis(
    question_content: str = Body(...),
    options: List[str] = Body(...)
):
    """技巧分析"""
    # 获取完整的技巧分析
    strategy = await question_technique_service.suggest_strategy(
        question_content,
        options
    )
    
    # 获取关键词分析
    keywords = await question_technique_service.identify_keywords(question_content)
    
    # 获取陷阱检测
    traps = await question_technique_service.detect_traps(question_content, options)
    
    # 获取选项分析
    option_analysis = await question_technique_service.analyze_options(
        question_content,
        options
    )
    
    return {
        "strategy": strategy,
        "keywords": keywords,
        "traps": traps,
        "option_analysis": option_analysis
    }


# 辅助函数
def _generate_reasoning_guidance(
    reasoning_chain: Dict[str, Any],
    key_facts: List[Dict[str, Any]]
) -> List[str]:
    """生成推理引导"""
    steps = []
    
    completeness = reasoning_chain.get("reasoning_completeness", {})
    
    if not completeness.get("has_major_premise", False):
        steps.append("第一步：识别相关法律条文（大前提）")
    
    if not completeness.get("has_minor_premise", False):
        steps.append("第二步：提取题目中的关键事实（小前提）")
    elif key_facts:
        steps.append(f"已识别{len(key_facts)}个关键事实，继续分析")
    
    if not completeness.get("has_conclusion", False):
        steps.append("第三步：基于大前提和小前提，推导结论")
    
    return steps if steps else ["推理链条完整，可以继续验证答案"]


def _generate_trap_warnings(traps: List[Dict[str, Any]]) -> List[str]:
    """生成陷阱警告"""
    warnings = []
    
    high_severity_traps = [t for t in traps if t.get("severity") == "high"]
    for trap in high_severity_traps:
        warnings.append(trap.get("description", "注意题目陷阱"))
    
    return warnings if warnings else []

